package com.wenlin.myproduction.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wenlin.myproduction.R;
import com.wenlin.myproduction.base.BaseActivity;
import com.wenlin.myproduction.base.BaseSwipeActivity;
import com.wenlin.myproduction.bean.GameOption;
import com.wenlin.myproduction.bean.GamePlayer;
import com.wenlin.myproduction.bean.TitleBean;
import com.wenlin.myproduction.binder.GameOptionBinder;
import com.wenlin.myproduction.binder.GamePlayerBinder;
import com.wenlin.myproduction.binder.GameTitleBinder;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.ESportsManagerDataUtil;
import com.wenlin.myproduction.util.LogUtils;
import com.wenlin.myproduction.util.MyGridLayoutManager;
import com.wenlin.myproduction.util.ToastUtils;
import com.wenlin.myproduction.util.TypeData;
import com.wenlin.myproduction.util.TypeDataNames;
import com.wenlin.myproduction.util.UI;
import com.wenlin.myproduction.util.ValCommon;
import com.wenlin.myproduction.util.ValGame;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author 文琳
 * @Email 377979485@qq.com
 * @desc
 * @time 2022-09-03 星期六 12:43
 */
public class ESportsManagerRecruitmentCalculatorActivity extends BaseSwipeActivity {
    @BindView(R.id.rv_options)
    RecyclerView rvOptions;
    @BindView(R.id.rv_results)
    RecyclerView rvResults;
    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.et)
    EditText et;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.rg2)
    RadioGroup rg2;
    @BindView(R.id.cb)
    CheckBox cb;
    private boolean isMultiCheck = false;
    private boolean isUnion = false;
    private boolean isShowThreeAndMore = false;
    private Items itemsOptions = new Items();
    private Items itemsResults = new Items();
    private MultiTypeAdapter adapterOptions;
    private MultiTypeAdapter adapterResults;

    public static void start(BaseActivity activity) {
        Intent intent = new Intent(activity, ESportsManagerRecruitmentCalculatorActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_e_sports_manager_recruitment_calculator;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(ValCommon.E_SPORTS_MANAGER_CALCULATOR);
        adapterOptions = new MultiTypeAdapter(itemsOptions);
        adapterOptions.register(TitleBean.class, new GameTitleBinder());
        adapterOptions.register(GameOption.class, new GameOptionBinder());
        MyGridLayoutManager manager = new MyGridLayoutManager(this, 5);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return itemsOptions.get(position) instanceof TitleBean ? 5 : 1;
            }
        });
        rvOptions.setLayoutManager(manager);
        rvOptions.setHasFixedSize(true);
        rvOptions.setAdapter(adapterOptions);
        //
        adapterResults = new MultiTypeAdapter(itemsResults);
        adapterResults.register(GamePlayer.class, new GamePlayerBinder());
        rvResults.setLayoutManager(new MyGridLayoutManager(this, 6));
        rvResults.setHasFixedSize(true);
        rvResults.setAdapter(adapterResults);

        loadOptions();

        rg.setOnCheckedChangeListener((group, checkedId) -> {
            isMultiCheck = checkedId == R.id.rb_2;
            ToastUtils.getInstance().showInfo("当前模式是“" + (isMultiCheck ? "多" : "单") + "选”");
            if (Checker.hasList(itemsOptions)) {
                itemsOptions.clear();
                adapterOptions.notifyDataSetChanged();
                loadOptions();
            }
            if (Checker.hasList(itemsResults)) {
                itemsResults.clear();
                adapterResults.notifyDataSetChanged();
            }
            search();
        });

        rg2.setOnCheckedChangeListener((group, checkedId) -> {
            isUnion = checkedId == R.id.rb_22;
            ToastUtils.getInstance().showInfo("当前模式是求“" + (isUnion ? "并" : "交") + "集”");
            if (Checker.hasList(itemsOptions)) {
                itemsOptions.clear();
                adapterOptions.notifyDataSetChanged();
                loadOptions();
            }
            if (Checker.hasList(itemsResults)) {
                itemsResults.clear();
                adapterResults.notifyDataSetChanged();
            }
            search();
        });

        cb.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isShowThreeAndMore = isChecked;
            search();
        });

        search();
    }

    /**
     * 加载选项列表
     */
    private void loadOptions() {
        itemsOptions.add(new TitleBean(ValGame.TITLE_DISTRICT));
        for (String string :
                ValGame.DISTRICTS) {
            itemsOptions.add(new GameOption(string, ValGame.TITLE_DISTRICT));
        }
        itemsOptions.add(new TitleBean(ValGame.TITLE_PARTY));
        for (String string :
                ValGame.PARTIES) {
            itemsOptions.add(new GameOption(string, ValGame.TITLE_PARTY));
        }
        itemsOptions.add(new TitleBean(ValGame.TITLE_POSITION));
        for (String string :
                ValGame.POSITIONS) {
            itemsOptions.add(new GameOption(string, ValGame.TITLE_POSITION));
        }
        itemsOptions.add(new TitleBean(ValGame.TITLE_PRO));
        for (String string :
                ValGame.PROS) {
            itemsOptions.add(new GameOption(string, ValGame.TITLE_PRO));
        }
        itemsOptions.add(new TitleBean(ValGame.TITLE_PRO2));
        for (String string :
                ValGame.PROS2) {
            itemsOptions.add(new GameOption(string, ValGame.TITLE_PRO2));
        }
//        itemsOptions.add(new TitleBean(ValGame.TITLE_QUALITY));
//        for (String string :
//                ValGame.QUALITIES) {
//            itemsOptions.add(new GameOption(string, ValGame.TITLE_QUALITY));
//        }
    }

    /**
     * 搜索
     */
    private void search() {
        if (isUnion) {
            searchUnion();
        } else {
            searchIntersection();
        }
    }

    /**
     * 求交集搜索
     */
    private void searchIntersection() {
        String keyOfName = UI.getEtText(et);
        StringBuilder district = new StringBuilder();
        StringBuilder party = new StringBuilder();
        StringBuilder position = new StringBuilder();
        StringBuilder pro = new StringBuilder();
        StringBuilder pro2 = new StringBuilder();
        if (Checker.hasList(itemsOptions)) {
            for (Object o :
                    itemsOptions) {
                if (o instanceof GameOption) {
                    GameOption gameOption = (GameOption) o;
                    String type = gameOption.getType();
                    if (Checker.hasNoWord(type)) {
                        LogUtils.e("未找到type " + gameOption.getName());
                        continue;
                    }
                    if (!gameOption.isSelected()) continue;
                    if (type.equals(ValGame.TITLE_DISTRICT)) {
                        district.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PARTY)) {
                        party.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_POSITION)) {
                        position.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PRO)) {
                        pro.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PRO2)) {
                        pro2.append(gameOption.getName()).append(",");
                    }
                }
            }
        }
        List<GamePlayer> list = ESportsManagerDataUtil.searchIntersection(district.toString(),
                party.toString(), position.toString(), pro.toString(), pro2.toString(), keyOfName);
        if (Checker.hasList(itemsResults)) {
            itemsResults.clear();
            adapterResults.notifyDataSetChanged();
        }
        if (isShowThreeAndMore) {//筛选契合度大于2的结果
            List<GamePlayer> newList = new ArrayList<>();
            for (GamePlayer gamePlayer :
                    list) {
                if (gamePlayer.getScore() > 2) {
                    newList.add(gamePlayer);
                }
            }
            itemsResults.addAll(newList);
        } else {
            itemsResults.addAll(list);
        }
        adapterResults.notifyDataSetChanged();
        UI.setText(tvResult, "搜索到" + itemsResults.size() + "个结果");
    }

    /**
     * 求并集搜索
     */
    private void searchUnion() {
        String keyOfName = UI.getEtText(et);
        StringBuilder district = new StringBuilder();
        StringBuilder party = new StringBuilder();
        StringBuilder position = new StringBuilder();
        StringBuilder pro = new StringBuilder();
        StringBuilder pro2 = new StringBuilder();
        if (Checker.hasList(itemsOptions)) {
            for (Object o :
                    itemsOptions) {
                if (o instanceof GameOption) {
                    GameOption gameOption = (GameOption) o;
                    String type = gameOption.getType();
                    if (Checker.hasNoWord(type)) {
                        LogUtils.e("未找到type " + gameOption.getName());
                        continue;
                    }
                    if (!gameOption.isSelected()) continue;
                    if (type.equals(ValGame.TITLE_DISTRICT)) {
                        district.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PARTY)) {
                        party.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_POSITION)) {
                        position.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PRO)) {
                        pro.append(gameOption.getName()).append(",");
                    } else if (type.equals(ValGame.TITLE_PRO2)) {
                        pro2.append(gameOption.getName()).append(",");
                    }
                }
            }
        }
        List<GamePlayer> list = ESportsManagerDataUtil.searchUnion(district.toString(),
                party.toString(), position.toString(), pro.toString(), pro2.toString(), keyOfName);
        if (Checker.hasList(itemsResults)) {
            itemsResults.clear();
            adapterResults.notifyDataSetChanged();
        }
        if (isShowThreeAndMore) {//筛选契合度大于2的结果
            List<GamePlayer> newList = new ArrayList<>();
            for (GamePlayer gamePlayer :
                    list) {
                if (gamePlayer.getScore() > 2) {
                    newList.add(gamePlayer);
                }
            }
            itemsResults.addAll(newList);
        } else {
            itemsResults.addAll(list);
        }
        adapterResults.notifyDataSetChanged();
        UI.setText(tvResult, "搜索到" + itemsResults.size() + "个结果");
    }

    @OnClick({R.id.tv_search})
    void click(View view) {
        int id = view.getId();
        if (id == R.id.tv_search) {
            search();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void threadHandle(TypeData typeData) {
        String name = typeData.getName();
        if (name.equals(TypeDataNames.clickGameOption)) {
            GameOption bean = (GameOption) typeData.getData();
            if (Checker.isNull(bean)) return;
            for (Object o :
                    itemsOptions) {
                if (o instanceof GameOption) {
                    GameOption gameOption = (GameOption) o;
                    if (gameOption.getType().equals(bean.getType())) {//同类型选项
                        if (isMultiCheck) {//求并集时，直接改变选中状态即可
                            if (gameOption.getName().equals(bean.getName())) {
                                gameOption.setSelected(!bean.isSelected());
                                adapterOptions.notifyDataSetChanged();
                                break;
                            }
                        } else {//求交集时，将其他同类型的已选中的选项取消选中
                            if (bean.isSelected() || !gameOption.getName().equals(bean.getName())) {
                                gameOption.setSelected(false);
                            } else {
                                gameOption.setSelected(true);
                            }
                            adapterOptions.notifyDataSetChanged();
                        }
                    }
                }
            }
            search();
        }
    }
}
